import mongoose, { Document, Schema } from 'mongoose';

export interface IMenu extends Document {
  // 核心必填字段
  // name: string;
  path: string;
  component: string;
  type: 'contents' | 'page';
  title: string;
  sort: number;
  isActive: boolean;
  // 结构与关系
  parentId: mongoose.Schema.Types.ObjectId | null;
  redirect?: string;
  //导航与 UI 显示字段
  // alwaysShow?: boolean;
  breadcrumb?: boolean;
  noCache?: boolean;
  affix?: boolean;
  linkSrc?: string;
  newWindow?: boolean;
  icon?: string;
  hidden: boolean;
  // 权限与安全
  tenantId?: mongoose.Schema.Types.ObjectId;
  // 扩展字段
  meta?: Record<string, any>;
  // 结构与关系
  createdAt: Date;
  updatedAt: Date;
  createdBy: mongoose.Schema.Types.ObjectId,
  updatedBy: mongoose.Schema.Types.ObjectId,

  //权限
  permissions: [mongoose.Schema.Types.ObjectId]
}
const menuSchema = new Schema<IMenu>({
  //菜单路径
  path: {
    type: String,
    required: [true, '菜单路径是必填项'],
    trim: true
  },
  //菜单类型
  type: {
    type: String,
    enum: ['contents', 'page'],
    default: 'page'
  },
  //组件路径
  component: {
    type: String,
    trim: true
  },
  //权限
  permissions: [{
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Permission'
  }],
  //菜单标题
  title: {
    type: String,
    required: [true, '菜单标题是必填项'],
    trim: true
  },
  //菜单排序
  sort: {
    type: Number,
    required: [true, '菜单排序是必填项'],
    min: [0, '菜单排序不能小于0']
  },
  //是否激活
  isActive: {
    type: Boolean,
    default: true
  },
  //是否显示面包屑
  breadcrumb: {
    type: Boolean,
    default: true
  },
  //是否禁用缓存
  noCache: {
    type: Boolean,
    default: false
  },
  //是否固定在标签页
  affix: {
    type: Boolean,
    default: false
  },
  //链接地址
  linkSrc: {
    type: String,
    trim: true
  },
  tenantId: {
    type: Schema.Types.ObjectId,
    required: [true, '租户ID是必填项'],
    ref: 'Tenant'
  },
  //是否新窗口打开
  newWindow: {
    type: Boolean,
    default: false
  },
  //图标
  icon: {
    type: String,
    trim: true
  },
  //是否隐藏
  hidden: {
    type: Boolean,
    default: false
  },
  //父级菜单ID
  parentId: {
    type: Schema.Types.ObjectId,
    ref: 'Menu',
    default: null
  },
  //重定向路径
  redirect: {
    type: String,
    trim: true
  },

  //元数据
  meta: {
    type: Object,
    default: {}
  },
  createdBy: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User',

  },
  updatedBy: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User',

  },
}, {
  timestamps: true // 自动添加 createdAt 和 updatedAt
});

// 创建索引
menuSchema.index({ path: 1, tenantId: 1 }, { unique: true });


export const MenuModel = mongoose.model<IMenu>('Menu', menuSchema);
